package com.example.rpc;

import cn.hutool.core.util.ObjectUtil;
import com.example.protocol.PackMsg;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName ResponseHandler
 * @Description TODO
 * @Author: XMK
 * @Date: 2020/9/30 14:16
 * @Version: 1.0
 */
public class ResponseHandler {
    private static ConcurrentHashMap<Long, CompletableFuture> map = new ConcurrentHashMap<>();

    public static void addCallback(long requestID, CompletableFuture callback) {
        map.putIfAbsent(requestID, callback);
    }

    public static void runCallback(PackMsg packMsg) {
        long requestID = packMsg.getHeader().getRequestID();
        CompletableFuture future = map.get(requestID);
        if (ObjectUtil.isNotNull(future)) {
            future.complete(packMsg.getRespBody().getMsg());
            removeCallback(requestID);
        }
    }

    public static void removeCallback(long requestID) {
        map.remove(requestID);
    }
}
